#include <stdio.h>
#include <syslog.h>
#include <errno.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>

#define FLNAME	"/etc/out"
#define BUFSIZE	128

int mydaemon(void);

int main(void)
{
	FILE *fp = NULL;
	time_t tm;
	struct tm *tmp = NULL;
	char buf[BUFSIZE] = {0};

	openlog("06mydaemon", LOG_PID, LOG_DAEMON);

	if (-1 == mydaemon()) {
		// fprintf(stderr, "mydaemon() error");
		syslog(LOG_ERR, "mydaemon() error");
		exit(1);
	}

	fp = fopen(FLNAME, "w");
	if (NULL == fp) {
// 		perror("fopen()");
		syslog(LOG_ERR, "fopen():%s", strerror(errno));
		exit(1);
	}

	while (1) {
		time(&tm);	
		tmp = localtime(&tm);
		if (NULL == tmp)
			break;
		memset(buf, '\0', BUFSIZE);
		strftime(buf, BUFSIZE, "%y/%m/%d %H:%M:%S\n", tmp);
		// 写入文件
		rewind(fp);
		fputs(buf, fp); // 全缓存
		printf("%s", buf);
		fflush(NULL);
		sleep(1);
	}

	return 0;
}

int mydaemon(void)
{
	pid_t pid;
	int fd;

	umask(0);

	pid = fork();
	if (-1 == pid) {
// 		perror("fork()");
		syslog(LOG_ERR, "fork():%s", strerror(errno));
		return -1;
	}
	if (pid > 0) {
		// 父进程终止
		_exit(0);
	}

	if (-1 == setsid()) {
		// perror("setsid()");
		syslog(LOG_ERR, "setsid():%s", strerror(errno));
		return -1;
	}
	chdir("/");

	fd = open("/dev/null", O_RDWR);
	if (-1 == fd) {
		syslog(LOG_ERR, "open():%s", strerror(errno));
		return -1;
	}
	dup2(fd, 0);
	dup2(fd, 1);
	dup2(fd, 2);

	return 0;
}



